package com.xyc.redis.controller;

import com.xyc.redis.utils.CodeUtil;
import com.xyc.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class CodeController {

    @Autowired
    @Qualifier("redisTemplate")
    RedisTemplate redisTemplate;

    @Autowired
    RedisUtil redisUtil;

    // 生产验证码 有效期为一分钟
    @RequestMapping("/doCode")
    public boolean code(HttpServletRequest req) {
        try {
            String ip = req.getRemoteAddr();
            String code = new CodeUtil().getCode();
            System.out.println("验证码为:" + code);

            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(ip + "_code", code);
            redisUtil.expire(ip + "_code", 60);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    //校验验证码
    @RequestMapping("/login")
    public String login(HttpServletRequest req, String code) {
        String ip = req.getRemoteAddr();
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String old_code = forValue.get(ip + "_code");
        if (old_code == null)
            return "验证码不存在或者过期";
        else if (old_code.equals(code))
            return "验证码正确";
        else
            return "验证码错误";
    }
}
